package GUI.Racks;

import BE.BELogAudit;
import BE.BEPosicionxRack;
import BE.BERack;
import BE.BEUsuario;
import BL.BLCombo;
import BL.BLLogAudit;
import BL.BLPosicionxrack;
import BL.BLRack;
import BL.BLValidaciones;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.Timestamp;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class GUIModificarRack extends javax.swing.JDialog {

    BERack beRack = null;
    BEUsuario objUsuario;
    List <BEPosicionxRack> posiciones=new ArrayList<BEPosicionxRack>();
    private  int idrack;
    /** Creates new form GUIModificarRack */
    public GUIModificarRack(java.awt.Frame parent, boolean modal, int idRack) {
        super(parent, modal);
        initComponents();
        inicializa();
        llenaVentana(idRack);
        this.idrack=idRack;
        
    }

    GUIModificarRack(java.awt.Frame object, boolean b, int idRack, BEUsuario Usuario) {
        super(object, b);
        initComponents();
        objUsuario=Usuario;
        inicializa();
        llenaVentana(idRack);
        this.idrack=idRack;
    }

    public void inicializa()
    {
        this.setLocationRelativeTo(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        this.setLocation(width/2-this.getWidth()/2, height/2-this.getHeight()/2);
        
        BLCombo bLCombo = new BLCombo();
        bLCombo.setCombo("ZONAS",1,cmbZona);
        
        
            cmbEstado.addItem(new BLCombo(2,"TODOS"));
        cmbEstado.addItem(new BLCombo(1,"ACTIVO"));
        cmbEstado.addItem(new BLCombo(0,"INACTIVO"));


    }

    public void llenaVentana (int idRack)
    {
        BLRack blRack = new BLRack();
        beRack = blRack.getRackbyId(idRack);

        if (beRack != null)
        {
            int i = 0;
            for (i=0;i<cmbZona.getModel().getSize();i++)
            {
                BLCombo s = (BLCombo)cmbZona.getModel().getElementAt(i);
                if (s.id == beRack.getIdzona())
                    break;
            }
            cmbZona.setSelectedIndex(i);
            
            txtNombre.setText(beRack.getNombre());
            txtNumeroFilas.setText(beRack.getNumeroFilas() + "");
            txtNumeroCol.setText(beRack.getNumeroColumnas() + "");
            txtX.setText(beRack.getPosicion().getFila() + "");
            txtY.setText(beRack.getPosicion().getColumna() + "");

            BLPosicionxrack blpxr = new BLPosicionxrack();
            posiciones=blpxr.posicionebyRack(idRack);
            llenarTabla(posiciones);

        }




    }
public void llenarTabla(List <BEPosicionxRack> lista){



   DefaultTableModel modelo=(DefaultTableModel) tblPXR.getModel();
for (int i=modelo.getRowCount()-1;i>=0;i--){
    modelo.removeRow(i);
}

if (lista!=null){
    for (int i = 0; i < lista.size(); i++) {
        modelo.addRow(new Object[5]);
        tblPXR.setValueAt(lista.get(i).getIdposicionxrack(), i, 0);

        tblPXR.setValueAt(lista.get(i).getFila(), i, 1);

        tblPXR.setValueAt(lista.get(i).getColumna(), i, 2);



        tblPXR.setValueAt(lista.get(i).getEstado(), i, 3);
        String estado;
        if (lista.get(i).getEstado()==0)
           estado="Activo";
        else if (lista.get(i).getEstado()==1)
            estado="Ocupado";
        
        else estado="Inactivo";
        
        tblPXR.setValueAt(estado, i, 4);
    }
    }
}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        pnlDatosBasicos = new javax.swing.JPanel();
        txtRack = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        lbZona = new javax.swing.JLabel();
        cmbZona = new javax.swing.JComboBox();
        txtNumeroFilas = new javax.swing.JTextField();
        lbNumFilas = new javax.swing.JLabel();
        txtNumeroCol = new javax.swing.JTextField();
        lbNumCol = new javax.swing.JLabel();
        lblX = new javax.swing.JLabel();
        lblY = new javax.swing.JLabel();
        txtX = new javax.swing.JTextField();
        txtY = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblPXR = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        btnAgregar = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        cmbEstado = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Editar Rack");

        pnlDatosBasicos.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Rack"));

        txtRack.setText("Rack:");

        txtNombre.setEnabled(false);

        lbZona.setText("Zona:");

        cmbZona.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbZonaItemStateChanged(evt);
            }
        });

        txtNumeroFilas.setEnabled(false);

        lbNumFilas.setText("Numero de Filas:");

        txtNumeroCol.setEnabled(false);

        lbNumCol.setText("Numero de Columnas:");

        lblX.setText("Posicion X inicial:");

        lblY.setText("Posicion Y inicial:");

        javax.swing.GroupLayout pnlDatosBasicosLayout = new javax.swing.GroupLayout(pnlDatosBasicos);
        pnlDatosBasicos.setLayout(pnlDatosBasicosLayout);
        pnlDatosBasicosLayout.setHorizontalGroup(
            pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDatosBasicosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbNumCol)
                    .addComponent(txtRack)
                    .addComponent(lbNumFilas)
                    .addComponent(lbZona)
                    .addComponent(lblX)
                    .addComponent(lblY))
                .addGap(13, 13, 13)
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtY, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                    .addComponent(cmbZona, 0, 170, Short.MAX_VALUE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                    .addComponent(txtNumeroFilas, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                    .addComponent(txtNumeroCol, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                    .addComponent(txtX, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnlDatosBasicosLayout.setVerticalGroup(
            pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDatosBasicosLayout.createSequentialGroup()
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRack)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbZona)
                    .addComponent(cmbZona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbNumFilas)
                    .addComponent(txtNumeroFilas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbNumCol)
                    .addComponent(txtNumeroCol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblX)
                    .addComponent(txtX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlDatosBasicosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblY)
                    .addComponent(txtY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tblPXR.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Posicion", "Piso", "Columna", "idEstado", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblPXR.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tblPXR);
        tblPXR.getColumnModel().getColumn(0).setResizable(false);
        tblPXR.getColumnModel().getColumn(1).setResizable(false);
        tblPXR.getColumnModel().getColumn(2).setResizable(false);
        tblPXR.getColumnModel().getColumn(3).setMinWidth(0);
        tblPXR.getColumnModel().getColumn(3).setPreferredWidth(0);
        tblPXR.getColumnModel().getColumn(3).setMaxWidth(0);
        tblPXR.getColumnModel().getColumn(4).setResizable(false);

        btnAgregar.setText("Aceptar");
        btnAgregar.setMaximumSize(new java.awt.Dimension(100, 25));
        btnAgregar.setMinimumSize(new java.awt.Dimension(100, 25));
        btnAgregar.setPreferredSize(new java.awt.Dimension(100, 25));
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnClose.setText("Cancelar");
        btnClose.setMaximumSize(new java.awt.Dimension(100, 25));
        btnClose.setMinimumSize(new java.awt.Dimension(100, 25));
        btnClose.setPreferredSize(new java.awt.Dimension(100, 25));
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(296, Short.MAX_VALUE)
                .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        cmbEstado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbEstadoActionPerformed(evt);
            }
        });

        jLabel1.setText("Cambiar Estado:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(pnlDatosBasicos, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                                .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel1)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlDatosBasicos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(55, 55, 55)))
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getAccessibleContext().setAccessibleDescription("GUIModicarRack");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.dispose();
}//GEN-LAST:event_btnCloseActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        BLRack blRack = new BLRack();
        int retorno;

        
        BLCombo idZona = (BLCombo)cmbZona.getSelectedItem();
        beRack.setIdzona(idZona.id);
        

        retorno = blRack.modificaRack(beRack,txtX.getText(), txtY.getText());
        if (retorno ==0)
        {
            BLLogAudit objgestorAdit = new BLLogAudit();
            BELogAudit objlogAudit= new BELogAudit();
            
            objlogAudit.setIdUsuario(objUsuario.getIdUsuario());
            objlogAudit.setIdInterface(0);
            objlogAudit.setIdUsuario(objUsuario.getIdUsuario());
            objlogAudit.setAccion("Edicion del rack "+beRack.getNombre() +" por el usuario "+objUsuario.getUsuario()+"." );
            Date aux= new Date();
            Timestamp fecha= new Timestamp(aux.getTime());
            
            objlogAudit.setFecha(fecha);
            
            objgestorAdit.registrarAccion(objlogAudit);
            
            
            
            JOptionPane.showMessageDialog(null,"Se ha editado el rack",
                                               "Información",JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
        }
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void cmbZonaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbZonaItemStateChanged
        txtX.setText("");
        txtY.setText("");
    }//GEN-LAST:event_cmbZonaItemStateChanged

private void cmbEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbEstadoActionPerformed
        int fila;
        int columna = 0;
        int idPos;
        int estado;

        fila = tblPXR.getSelectedRowCount();
 

//        if (fila <= 0 )
//            JOptionPane.showMessageDialog(null,"Debe seleccionar una posición en el rack para editar",
//                                    "Información",JOptionPane.INFORMATION_MESSAGE);

        if (fila > 0 && JOptionPane.showConfirmDialog(null,"¿Desea cambiar el estado de la posición?",
                 "Confirmación",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE) == 0)
        {  BLCombo idEstado = (BLCombo)cmbEstado.getSelectedItem();
             // System.out.println(idEstado.id);
            fila = tblPXR.getSelectedRow();
            estado=Integer.parseInt(tblPXR.getModel().getValueAt(fila,3).toString());
          if (estado==1){
          JOptionPane.showMessageDialog(null,"Debe seleccionar una posicion libre",
                                          "Informacion",JOptionPane.INFORMATION_MESSAGE);
       return;}
            idPos = Integer.parseInt(tblPXR.getModel().getValueAt(fila,columna).toString());

          BLPosicionxrack blPXR= new BLPosicionxrack();
        

          
          if (idEstado.id==0)
              estado=2;
          else if (idEstado.id==1)
              estado=0;

        
          blPXR.cambiarEstado2(idPos,estado);

          posiciones=blPXR.posicionebyRack(idrack);
            llenarTabla(posiciones);
            
            cmbEstado.setSelectedIndex(0);
}//GEN-LAST:event_cmbEstadoActionPerformed
}
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                GUIModificarRack dialog = new GUIModificarRack(new javax.swing.JFrame(), true, 0);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnClose;
    private javax.swing.JComboBox cmbEstado;
    private javax.swing.JComboBox cmbZona;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lbNumCol;
    private javax.swing.JLabel lbNumFilas;
    private javax.swing.JLabel lbZona;
    private javax.swing.JLabel lblX;
    private javax.swing.JLabel lblY;
    private javax.swing.JPanel pnlDatosBasicos;
    private javax.swing.JTable tblPXR;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtNumeroCol;
    private javax.swing.JTextField txtNumeroFilas;
    private javax.swing.JLabel txtRack;
    private javax.swing.JTextField txtX;
    private javax.swing.JTextField txtY;
    // End of variables declaration//GEN-END:variables

}
